import { defineConfig, loadEnv } from "vite";
import svgr from "vite-plugin-svgr";
import react from "@vitejs/plugin-react";
import autoprefixer from "autoprefixer";
import { fileURLToPath, URL } from "node:url";
import { createHtmlPlugin } from "vite-plugin-html";

// https://vitejs.dev/config/
export default defineConfig(config => {
  const mode = config.mode;
  const envDir = "./env";
  const envPrefix = ["ENV"];

  // 获取环境变量
  const getEnv = (key: string) => {
    return loadEnv(mode, envDir, envPrefix)[key];
  };

  return {
    envDir,
    envPrefix,
    build: {
      outDir: "./build",
      rollupOptions: {
        input: {
          index: './index.html'
        }
      }
    },
    server: {
      host: '0.0.0.0'
    },
    css: {
      postcss: {
        plugins: [autoprefixer(["Last 5 versions"])],
      },
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        }
      }
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "@@": fileURLToPath(new URL("./", import.meta.url)),
      },
    },
    plugins: [
      react(),
      svgr(),
      createHtmlPlugin({
        pages: [
          {
            filename: 'index',
            template: './index.html',
            injectOptions: {
              data: {
                title: getEnv("ENV_APP_NAME"),
              }
            }
          }
        ]
      }),
    ],
  };
});
